package com.tintuc24h.com;

import java.util.List;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import com.tintuc24h.adapter.PaperAdapter;
import com.tintuc24h.models.RssItem;
import com.tintuc24h.untils.Rssparse;
import com.tintuc24h.untils.Variables;

public class TheLoai extends ListActivity {

	private int paper;
	private ProgressDialog dialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Bundle bundle = getIntent().getExtras();
		paper = bundle.getInt(Variables.PAPER);
		setTitle(Variables.PAPERS[paper]);

		ArrayAdapter<String> adapter = new ArrayAdapter<String>(
				TheLoai.this,android.R.layout.simple_list_item_1,
				Variables.CATEGORIES[paper]);
		setListAdapter(adapter);
	}

	private Boolean isOnline() {
		    ConnectivityManager cm = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
		    NetworkInfo ni = cm.getActiveNetworkInfo();
		    if(ni != null && ni.isConnected()) {
		         return true;
		        }
		    return false;
	}
	
	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);
		if(isOnline()==true){
		dialog = ProgressDialog.show(TheLoai.this, "", "Loading...");
		new CategoryTask().execute(position);
		}
		else {
			Toast.makeText(this, "Hay ket noi mang internet", Toast.LENGTH_LONG).show();
		}
	}

	class CategoryTask extends AsyncTask<Integer, Void, Void> {
		private int position;

		@Override
		protected Void doInBackground(Integer... params) {
			position = params[0];
			int key = paper + 1000 + position;
			Rssparse parse = new Rssparse();
			List<RssItem> items = parse
					.getNewList(Variables.LINK[paper][position]);
			Variables.newhashmap.put(key, items);

			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			if (dialog != null) {
				dialog.dismiss();
			}
			Intent intent = new Intent(TheLoai.this, NewsItemList.class);
			intent.putExtra(Variables.PAPER, paper);
			intent.putExtra(Variables.CATEGORY, position);
			startActivity(intent);
			super.onPostExecute(result);
		}
	}
}
